var windowInstallPage;
var id_timeout;

function isPageInstalled(id_page, options)
{
	var checkbox 		= options['checkbox'];
	var check_box_obj 	= options['check_box_obj'];
	result = FB.api('/' + id_page, function(response) {
		if (response.has_added_app)
		{
			checkbox.checked = true;
		}
		else
		{
			Social.getDialog().create({
				content: options['template'],
				closeIcon: true,
				onClose: function() {
					checkbox.checked = false;
					$(this).dialog("close");
				},
				onOk: function(){
					windowInstallPage = window.open(
						"http://www.facebook.com/add.php?api_key=" + social_app_id + "&pages=1&page=" + id_page,
						'_blank',
						'width=650,height=320,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no'
					);
					id_timeout = setTimeout(function(){
						checkPageInstalled(id_page,checkbox,check_box_obj)
					},5000);
					checkbox.checked = false;
					$(this).dialog("close");
				},
				visible: true
			});
		}
	});
    return false;
}

function checkPageInstalled(id_page, checkbox, check_box_obj)
{
	result = FB.api('/' + id_page, function(response) {
		if (response.has_added_app)
		{
			windowInstallPage.close();
			var image = " <img width='16' title='Already installed' src='" +static_url+ "/img/apply-icon.gif'/>";
			check_box_obj.parent().children('img').remove();
			check_box_obj.parent().append(image);
			checkbox.checked = true;
			var tabs_added  = {};
			tabs_added[id_page] = 1;
			$.get(base_url,{
				'tabs_added': tabs_added
			});
			alert(add_fanpage_successfully);
		}
		else
		{
			if( windowInstallPage && windowInstallPage.closed !== false )
			{
				id_timeout = setTimeout(function(){
					checkPageInstalled(id_page,checkbox, check_box_obj)
				},3000);
				checkbox.checked = false;
			}
		}
	});
}
function postToWall(title, desc, href, image, caption)
{
	FB.ui(
	{
		method: 'feed',
		app_id: social_app_id,
		name: title,
		link: href+'?ref='+social_user_id,
		picture: image,
		caption: caption,
		description: desc
	},
	function(response) {
		// nothing to do here
	}
);
}
function authorizeBeforeShare(share_url, permission)
{
	FB.getLoginStatus(function(response) {
		FB.login(
		function(response) {
			if (response.authResponse) {
				FB.api('/me', function(response) {
					share(response.id, share_url);
				});
			} else {
				alert('You need to authorize the application before you can vote, share or invite friends.')
			}
		}
		, {
			scope : permission || ''
		});
	});
}
function authorizeBeforeInvite(entry_title, url, permission)
{
	FB.getLoginStatus(function(response) {
		FB.login(
		function(response) {
			if (response.authResponse) {
				FB.api('/me', function(response) {
					inviteFriends(response.id, entry_title, url);
				});
			} else {
				alert('You need to authorize the application before you can vote, share or invite friends.')
			}
		}
		, {
			scope : permission || ''
		});
	});
}
function authorizeBeforeVote(redirect_url, permission)
{
	FB.getLoginStatus(function(response) {
		FB.login(
		function(response) {
			if (response.authResponse) {
				FB.api('/me', function(response) {
					top.location = redirect_url;
				});
			} else {
				alert('You need to authorize the application before you can vote, share or invite friends.')
			}
		}
		, {
			scope : permission || ''
		});
	});
}
function authorizeBeforeGotoSubmit(redirect_url, permission)
{
	authorizeBefore(redirect_url, 'You need to authorize the application before you can submit an entry', permission);
}
function authorizeBefore(redirect_url, msg, permission)
{
	FB.getLoginStatus(function(response) {
		FB.login(
		function(response) {
			if (response.authResponse) {
				FB.api('/me', function(response) {
					top.location = redirect_url;
				});
			} else {
				alert(msg)
			}
		}
		, {
			scope : permission || ''
		});
	});
}
function authorizeManagePages(redirect_url)
{
	FB.getLoginStatus(function(response) {
		FB.login(
		function(response) {
			if (response.authResponse) {
				FB.api('/me', function(response) {
					top.location.href = redirect_url;
				});
			} else {
				alert('You need to authorize the manage page permission before you can load your fanpages.')
			}
		}
		, {
			scope : 'manage_pages'
		});
	});
}
function share(share_url)
{
	window.open(
	'http://www.facebook.com/sharer/sharer.php?u=' + share_url,
	'popUpWindow',
	'width=650,height=320,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no'
);
	return false;
}

function inviteFriends(entry_title, url, id_user)
{
	FB.ui({
		method: 'send',
		name: entry_title,
		link: url + id_user,
		display:'popup'
	});
}
/****Code waiting to review******/
function sendAppRequests(message, data)
{
	if (data == undefined)
		FB.ui({
			method: 'apprequests',
			message: message
		});
	else
		FB.ui({
			method: 'apprequests',
			message: message,
			data: data
		});
}
/****Code waiting to review******/
function canvasScrollTo(left,top)
{
	FB.Canvas.scrollTo(left,top);
	FB.Canvas.setAutoGrow();
}


FanpageHandler = {}

FanpageHandler = function(arrFanpages, defaultPage, appliedIconUrl)
{
	this.arrFanpages = arrFanpages || [];
	this.defaultPage = defaultPage;
	this.appliedIconUrl = appliedIconUrl;
	this.isRunned = false;
}

FanpageHandler.prototype.loadFanpages = function()
{
	var fanpageHandler = this;
	FB.getLoginStatus(function(response) {
		if (response.status === 'connected')
		{
			FB.api('/me/permissions', function (response) {
				if(response.data[0].manage_pages==1)
				{
					fanpageHandler.showFanpages();
				}
				else
				{
					FB.login(function(response) {
						fanpageHandler.showFanpages();
					}, {
						scope : 'email, manage_pages'
					}
					);
				}
			});
		}
	});
}

FanpageHandler.prototype.showFanpages = function()
{
	var fanpageHandler = this;
	var reload = $("#reload").length;
	if(reload>0)
	{
		FB.api('/me/accounts', function(response) {
			var data		= response.data;
			var html		= '';
			var arrFanpages	= fanpageHandler.arrFanpages;
			for (id in data)
			{
				var page = data[id];
				if( page['category'] != 'Application')
				{
					var checked = " ";
					var disabled = " ";
					if( jQuery.inArray(page.id,arrFanpages) != -1)
					{
						checked = " checked='checked' ";
					}
					html += "<li><input type='checkbox'" + checked + "name='fanpages[]' value='" + page.id + "'> " + page.name + "</li>";
				}
			}

			if (html != '')
			{
				$('#load_my_fanpage').remove();
				$('.sm_listfan').html(html);
				$("input[name='fanpages[]']").each(function(){
					fanpageHandler.markPageInstalled($(this).val(), $(this));
				});
				fanpageHandler.checkPageByDefault(fanpageHandler.defaultPage,$('input[value="' + fanpageHandler.defaultPage + '"]'));
			}

			if(fanpageHandler.isRunned && html=='')
			{
				/*create new fanpage is defined in initHead in module facebook*/
				$('.sm_listfan').html('<li>No fanpage found - <a target="_parent" href="' + social_url_fanpage_create + '">Create a Page</a></li>');
			}
		});
	}
	else
	{
		$("input[name='fanpages[]']").each(function(){
			fanpageHandler.markPageInstalled($(this).val(), $(this));
		});
	}
}

FanpageHandler.prototype.markPageInstalled = function(id_page, item)
{
	var fanpageHandler = this;
	FB.api('/' + id_page, function(response) {
		if (response.has_added_app)
		{
			var image = " <img width='16' title='Already installed' src='" + fanpageHandler.appliedIconUrl + "'/>";
			item.parent().append(image);
		}
	});
}

FanpageHandler.prototype.checkPageByDefault = function(id_page, item)
{
	FB.api('/' + id_page, function(response) {
		if (response.has_added_app)
		{
			item.attr("checked","checked");
		}
	});
}

FanpageHandler.prototype.setIsRunned = function(value)
{
	this.isRunned = value;
}

$(document).ready(function(){
	$("input[name='fanpages[]']").live('click',function(){
		if(this.checked){
			var fanpage = $(this).val().split(':');
			isPageInstalled(fanpage[0],{
				checkbox:this,
				check_box_obj: $(this),
				template: confirm_template
			});
			return false;
		}
	});
	$('label[for="submit"]').html('&nbsp;');
});

function detectNewComment(url, data, callback)
{
    FB.Event.subscribe('comment.create', function(){
        $.post(
            url,
            data,
            callback
        );
    });
}

function authorizeBeforeAddToCart(callback)
{
	FB.getLoginStatus(function(response) {
        if (response.status !== 'connected') {
            FB.login(
                function(response) {
                    if (response.authResponse) {
                        FB.api('/me', function(response) {
                            callback();
                        });
                    } else {
					alert('You need to authorize the application before you can add a product to cart.')
				}
                }
                , {
                    scope : 'email'
                }
            );
        } else {
            callback();
        }
        
	});
}

function authorizeForOrder(callback)
{
	FB.getLoginStatus(function(response) {
		FB.login(
			function(response) {
				if (response.authResponse) {
					FB.api('/me', function(response) {
                        callback();
					});
				}
			}
			, {
				scope : 'email'
			}
        );
	});
}